package kz.pompei.ifacer.main;

import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

import kz.pompei.ifacer.conf.Config;

public class SizeLocationSaver {
  public final JFrame frame;
  public final String prefix;
  public final Config conf;
  
  private WindowState windowState;
  
  public SizeLocationSaver(JFrame jframe, String prefix1, Config config, int x, int y,
      int width, int height, WindowState state) {
    this.frame = jframe;
    this.prefix = prefix1;
    this.conf = config;
    
    windowState = state;
    
    frame.setLocation(conf.getInt(prefix + ".x", x), conf.getInt(prefix + ".y", y));
    frame.setSize(conf.getInt(prefix + ".width", width), conf.getInt(prefix + ".height", height));
    
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        windowState = WindowState.byName(conf.get(prefix + ".state"), windowState);
        windowState.applyTo(frame);
      }
    });
    
    frame.addComponentListener(new ComponentAdapter() {
      @Override
      public void componentMoved(ComponentEvent e) {
        savePosition();
      }
      
      @Override
      public void componentResized(ComponentEvent e) {
        savePosition();
      }
    });
    frame.addWindowStateListener(new WindowStateListener() {
      @Override
      public void windowStateChanged(WindowEvent e) {
        windowState = WindowState.convert(e.getNewState());
        savePosition();
      }
    });
  }
  
  private void savePosition() {
    conf.set(prefix + ".state", windowState.name());
    if (windowState == WindowState.NORMAL) {
      conf.setInt(prefix + ".x", frame.getX());
      conf.setInt(prefix + ".y", frame.getY());
      conf.setInt(prefix + ".width", frame.getWidth());
      conf.setInt(prefix + ".height", frame.getHeight());
    }
    conf.write();
  }
}
